package com.sh.fmbackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sh.fmbackend.common.BaseResponse;
import com.sh.fmbackend.common.ErrorCode;
import com.sh.fmbackend.common.ResultUtils;
import com.sh.fmbackend.exception.BusinessException;
import com.sh.fmbackend.model.domain.User;
import com.sh.fmbackend.model.request.UserLoginRequest;
import com.sh.fmbackend.model.request.UserRegisterRequest;
import com.sh.fmbackend.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.sh.fmbackend.constant.UserConstant.ADMIN_ROLE;
import static com.sh.fmbackend.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = {"http://localhost:3000","http://localhost:5173" })
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        long userId = currentUser.getId();
        User user = userService.getById(userId);
        User safetyUser = userService.getSafetyUser(user);
        return ResultUtils.success(safetyUser);
    }


    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Integer result = userService.updateUser(user, loginUser);
        return ResultUtils.success(result);
    }

    @PostMapping("/updateImg")
    public BaseResponse<Boolean> updateImg(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        Boolean result = userService.updateImg(file,request);
        return ResultUtils.success(result);
    }



    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) return ResultUtils.success(false);
        if (id < 0) {
            return ResultUtils.success(false);
        }
        boolean result = userService.removeById(id);
        return ResultUtils.success(result);
    }

    @GetMapping("/search/tags")
    public BaseResponse<List<User>> searchUsersByTags(@RequestParam(required = false) List<String> tags) {
        if (CollectionUtils.isEmpty(tags)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<User> users = userService.searchUserByTagsBySQL(tags);
        return ResultUtils.success(users);
    }


    @GetMapping("/recommend")
    public BaseResponse<Page<User>> recommendUsers(int pageSize, long pageNum, HttpServletRequest request) {
        // 缓存中有没有
        User loginUser = userService.getLoginUser(request);
        String key = String.format("sh:user:recommend:%s", loginUser.getId());
        Page<User> userList = (Page<User>) redisTemplate.opsForValue().get(key);
        // 缓存中有
        if (userList != null) {
            return ResultUtils.success(userList);
        }
        // 缓存中没有
        QueryWrapper<User> objectQueryWrapper = new QueryWrapper<>();
        Page<User> userPage = userService.page(new Page<>(pageNum, pageSize), objectQueryWrapper);
        // 脱敏
        List<User> desensitizedUserList = userPage.getRecords().stream() .map(user -> userService.getSafetyUser(user)) .collect(Collectors.toList());
        userPage.setRecords(desensitizedUserList);
        try {
            redisTemplate.opsForValue().set(key, userPage, 10, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("redis set error");
        }
        return ResultUtils.success(userPage);
    }


    /**
     * 获取最匹配的用户
     *
     * @param num     推荐数量
     * @param request
     * @return
     */
    @GetMapping("/match")
    public BaseResponse<List<User>> matchUsers(long num, HttpServletRequest request) {
        if (num <= 0 || num>20 ) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        List<User> res = userService.matchUsers(loginUser, num);
        return ResultUtils.success(res);
    }



}
